<!doctype html>
<html>
  <body>
    <script src="three.js"></script>
    <script>
let renderer, scene, camera, session, canvas, planeMesh, boxMeshes, controllerMeshes;

const localVector = new THREE.Vector3();
const localVector2 = new THREE.Vector3();
const localVector3 = new THREE.Vector3();
const localCoord = new THREE.Vector2();
const localPlane = new THREE.Plane();
const localLine = new THREE.Line3();
const localLine2 = new THREE.Line3();
const localRaycaster = new THREE.Raycaster();

const planeWorldWidth = 1;
const planeWorldHeight = 1;
const planeWidth = 600;
const planeHeight = planeWidth;

function init() {
  renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true,
  });
  renderer.setPixelRatio(window.devicePixelRatio);
  renderer.setSize(window.innerWidth, window.innerHeight);

  // window.browser.magicleap.RequestDepthPopulation(true);
  // renderer.autoClear = false;

  document.body.appendChild(renderer.domElement);

  scene = new THREE.Scene();
  scene.matrixAutoUpdate = false;
  // scene.background = new THREE.Color(0x3B3961);

  camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 1000);
  // camera.position.set(0, 1, 0);
  // camera.lookAt(new THREE.Vector3());
  scene.add(camera);

  const ambientLight = new THREE.AmbientLight(0x808080);
  scene.add(ambientLight);

  const directionalLight = new THREE.DirectionalLight(0xFFFFFF, 1);
  directionalLight.position.set(1, 1, 1);
  scene.add(directionalLight);

  canvas = document.createElement('canvas');
  canvas.width = planeWidth;
  canvas.height = planeHeight;
  
  const context = canvas.getContext('2d');
  
  context.fillStyle = '#FFF';
  context.fillRect(0, 0, canvas.width, canvas.height);
  
  context.stokeStyle = "#000000";
  context.lineWidth  = 1;
  context.beginPath();
  context.moveTo(  0, 75);
  context.lineTo(500, 75);
  context.stroke();
  context.closePath();

  context.font      = "16px Verdana";
  context.fillStyle = "#000000";

  context.textBaseline = "top";
  context.fillText("top", 0, 75);

  context.textBaseline = "hanging";
  context.fillText("hanging", 40, 75);

  context.textBaseline = "middle";
  context.fillText("middle", 120, 75);

  context.textBaseline = "alphabetic";
  context.fillText("alphabetic", 200, 75);

  context.textBaseline = "ideographic";
  context.fillText("ideographic", 300, 75);

  context.textBaseline = "bottom";
  context.fillText("bottom", 400, 75);

  planeMesh = (() => {
    const geometry = new THREE.PlaneBufferGeometry(planeWorldWidth, planeWorldHeight)
      // .applyMatrix(new THREE.Matrix4().makeScale(-1, -1, 1));
    /* const material = new THREE.MeshPhongMaterial({
      color: 0xFFFF00,
    }); */
    const texture = new THREE.Texture(
      canvas,
      THREE.UVMapping,
      THREE.ClampToEdgeWrapping,
      THREE.ClampToEdgeWrapping,
      THREE.NearestFilter,
      THREE.NearestFilter,
      THREE.RGBAFormat,
      THREE.UnsignedByteType,
      16
    );
    texture.needsUpdate = true;
    const material = new THREE.MeshBasicMaterial({
      map: texture,
    });
    const mesh = new THREE.Mesh(geometry, material);
    mesh.position.z = -1;

    return mesh;
  })();
  scene.add(planeMesh);
}

init();

// let direction = true;
function animate(timestamp, frame) {
  /* if (direction) {
    planeMesh.rotation.y += 0.001;

    if (planeMesh.rotation.y >= Math.PI/8) {
      direction = false;
    }
  } else {
    planeMesh.rotation.y -= 0.001;

    if (planeMesh.rotation.y <= -Math.PI/8) {
      direction = true;
    }
  } */

  renderer.render(scene, camera);
}

if (navigator.xr) {
  (async () => {
    session = await navigator.xr.requestSession({
      exclusive: true,
    }).catch(err => Promise.resolve(null));

    if (session) {
      session.onselect = e => {
        console.log('select'); // XXX
      };

      session.requestAnimationFrame((timestamp, frame) => {
        renderer.vr.setSession(session, {
          frameOfReferenceType: 'stage',
        });

        const {views} = frame.getViewerPose();
        const viewport = session.baseLayer.getViewport(views[0]);
        const width = viewport.width;
        const height = viewport.height;

        renderer.setSize(width * 2, height);

        renderer.setAnimationLoop(null);

        renderer.vr.enabled = true;
        renderer.vr.setAnimationLoop(animate);

        console.log('running xr!');
      });
    } else {
      renderer.setAnimationLoop(animate);
      
      console.log('running 2d!');
    }
  })()
    .catch(err => {
      console.warn(err.stack);
    });
} else {
  renderer.setAnimationLoop(animate);
}

    </script>
  </body>
</html>
